'use strict';
const db = uniCloud.database();

/**
 * 云函数：重新提交错题答案
 * @param {Object} event - 请求参数
 * @param {string} event.user_id - 用户ID
 * @param {string} event.wrong_question_id - 错题ID
 * @param {string} event.user_answer - 用户答案
 * @returns {Object} - 提交结果
 */
exports.main = async (event, context) => {
  const { user_id, wrong_question_id, user_answer } = event;

  // 参数校验
  if (!user_id || !wrong_question_id || !user_answer) {
    return { code: -1, msg: '参数缺失' };
  }

  try {
    const wrongQuestionCollection = db.collection('wrong_questions');
    const questionCollection = db.collection('questions');

    // 获取错题记录
    const wrongRes = await wrongQuestionCollection.doc(wrong_question_id).get();
    if (!wrongRes.data.length) {
      return { code: -1, msg: '错题不存在' };
    }
    const wrongQuestion = wrongRes.data[0];

    // 获取原始题目以获取正确答案
    const questionRes = await questionCollection.doc(wrongQuestion.question_id).get();
    if (!questionRes.data.length) {
      return { code: -1, msg: '原始题目不存在' };
    }
    const question = questionRes.data[0];
    const correctAnswer = question.answer;

    // 验证答案
    const isCorrect = user_answer.toUpperCase() === correctAnswer.toUpperCase();

    if (isCorrect) {
      // 回答正确：移除错题，不加积分
      await wrongQuestionCollection.doc(wrong_question_id).remove();
      return {
        code: 0,
        data: { points: 0 },
        msg: '回答正确，错题已移除'
      };
    } else {
      // 回答错误：更新错题记录
      await wrongQuestionCollection.doc(wrong_question_id).update({
        user_answer: user_answer.toUpperCase(),
        updated_at: Date.now()
      });
      return {
        code: 0,
        data: { points: 0 },
        msg: '回答错误，错题已更新'
      };
    }
  } catch (e) {
    console.error('重新提交错题失败:', e);
    return { code: -1, msg: '重新提交错题失败' };
  }
};